<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />









  <meta name="baidu-site-verification" content="Q7ugSRSO7V" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="并发编程示例定时任务func demo(input chan interface&amp;#123;&amp;#125;) &amp;#123;    t1 := time.NewTimer(time.Second * 5)    t2 := time.NewTimer(time.Second * 10)    for &amp;#123;        select &amp;#123;        case msg &amp;lt;- i">
<meta property="og:type" content="article">
<meta property="og:title" content="并发编程示例">
<meta property="og:url" content="http://yoursite.com/golang/并发编程示例/index.html">
<meta property="og:site_name" content="chimps">
<meta property="og:description" content="并发编程示例定时任务func demo(input chan interface&amp;#123;&amp;#125;) &amp;#123;    t1 := time.NewTimer(time.Second * 5)    t2 := time.NewTimer(time.Second * 10)    for &amp;#123;        select &amp;#123;        case msg &amp;lt;- i">
<meta property="og:updated_time" content="2017-08-04T01:58:54.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="并发编程示例">
<meta name="twitter:description" content="并发编程示例定时任务func demo(input chan interface&amp;#123;&amp;#125;) &amp;#123;    t1 := time.NewTimer(time.Second * 5)    t2 := time.NewTimer(time.Second * 10)    for &amp;#123;        select &amp;#123;        case msg &amp;lt;- i">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":30},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/golang/并发编程示例/"/>





  <title> 并发编程示例 | chimps </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?dcb994042608bdb310eff950ba755ff1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">chimps</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/golang/并发编程示例/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chimps">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="chimps">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                并发编程示例
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-14T18:32:37+08:00">
                2017-07-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/golang/" itemprop="url" rel="index">
                    <span itemprop="name">golang</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a class="cloud-tie-join-count" href="/golang/并发编程示例/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count join-count" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="并发编程示例"><a href="#并发编程示例" class="headerlink" title="并发编程示例"></a>并发编程示例</h1><h2 id="定时任务"><a href="#定时任务" class="headerlink" title="定时任务"></a>定时任务</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">demo</span><span class="params">(input <span class="keyword">chan</span> <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</div><div class="line">    t1 := time.NewTimer(time.Second * <span class="number">5</span>)</div><div class="line">    t2 := time.NewTimer(time.Second * <span class="number">10</span>)</div><div class="line"></div><div class="line">    <span class="keyword">for</span> &#123;</div><div class="line">        <span class="keyword">select</span> &#123;</div><div class="line">        <span class="keyword">case</span> msg &lt;- input:</div><div class="line">            <span class="built_in">println</span>(msg)</div><div class="line"></div><div class="line">        <span class="keyword">case</span> &lt;-t1.C:</div><div class="line">            <span class="built_in">println</span>(<span class="string">"5s timer"</span>)</div><div class="line">            t1.Reset(time.Second * <span class="number">5</span>)</div><div class="line"></div><div class="line">        <span class="keyword">case</span> &lt;-t2.C:</div><div class="line">            <span class="built_in">println</span>(<span class="string">"10s timer"</span>)</div><div class="line">            t2.Reset(time.Second * <span class="number">10</span>)</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="断续器"><a href="#断续器" class="headerlink" title="断续器"></a>断续器</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</div><div class="line">    ticker := time.NewTicker(time.Second)</div><div class="line">	<span class="keyword">for</span> t := <span class="keyword">range</span> ticker.C &#123;</div><div class="line">		fmt.Println(<span class="string">"ticker"</span>, t)</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="超时"><a href="#超时" class="headerlink" title="超时"></a>超时</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</div><div class="line">    ch1 := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>, <span class="number">1</span>)</div><div class="line">    ch2 := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>, <span class="number">1</span>)</div><div class="line"></div><div class="line">    <span class="keyword">select</span> &#123;</div><div class="line">        <span class="keyword">case</span> e1 := &lt;-ch1:</div><div class="line">        <span class="comment">//如果ch1通道成功读取数据，则执行该case处理语句</span></div><div class="line">            fmt.Printf(<span class="string">"1th case is selected. e1=%v"</span>,e1)</div><div class="line">        <span class="keyword">case</span> e2 := &lt;-ch2:</div><div class="line">        <span class="comment">//如果ch2通道成功读取数据，则执行该case处理语句</span></div><div class="line">            fmt.Printf(<span class="string">"2th case is selected. e2=%v"</span>,e2)</div><div class="line">        <span class="keyword">case</span> &lt;- time.After(<span class="number">2</span> * time.Second):</div><div class="line">            fmt.Println(<span class="string">"Timed out"</span>)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="自定义定时器"><a href="#自定义定时器" class="headerlink" title="自定义定时器"></a>自定义定时器</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</div><div class="line">    <span class="keyword">var</span> t *time.Timer</div><div class="line"></div><div class="line">    f := <span class="function"><span class="keyword">func</span><span class="params">()</span></span>&#123;</div><div class="line">        fmt.Printf(<span class="string">"Expiration time : %v.\n"</span>, time.Now())</div><div class="line">        fmt.Printf(<span class="string">"C`s len: %d\n"</span>, <span class="built_in">len</span>(t.C))</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    t = time.AfterFunc(<span class="number">1</span>*time.Second, f)</div><div class="line">    <span class="comment">//让当前Goroutine 睡眠2s，确保大于内容的完整</span></div><div class="line">    <span class="comment">//这样做原因是，time.AfterFunc的调用不会被阻塞。它会以一部的方式在到期事件来临执行我们自定义函数f。</span></div><div class="line">    time.Sleep(<span class="number">2</span> * time.Second)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="使用时间控制停止ticker"><a href="#使用时间控制停止ticker" class="headerlink" title="使用时间控制停止ticker"></a>使用时间控制停止ticker</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</div><div class="line">    <span class="comment">//初始化断续器,间隔2s</span></div><div class="line">    <span class="keyword">var</span> ticker *time.Ticker = time.NewTicker(<span class="number">1</span> * time.Second)</div><div class="line"></div><div class="line">    <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</div><div class="line">        <span class="keyword">for</span> t := <span class="keyword">range</span> ticker.C &#123;</div><div class="line">            fmt.Println(<span class="string">"Tick at"</span>, t)</div><div class="line">        &#125;</div><div class="line">    &#125;()</div><div class="line"></div><div class="line">    time.Sleep(time.Second * <span class="number">5</span>)   <span class="comment">//阻塞，则执行次数为sleep的休眠时间/ticker的时间</span></div><div class="line">    ticker.Stop()       <span class="comment">//停止ticker</span></div><div class="line">    fmt.Println(<span class="string">"Ticker stopped"</span>)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="并发读取文件夹所有文件的长度（使用通道）"><a href="#并发读取文件夹所有文件的长度（使用通道）" class="headerlink" title="并发读取文件夹所有文件的长度（使用通道）"></a>并发读取文件夹所有文件的长度（使用通道）</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">test1</span><span class="params">()</span></span> &#123;</div><div class="line">    <span class="comment">// 遍历文件夹，获取文件名</span></div><div class="line">	dir := <span class="string">"./db"</span></div><div class="line">	paths, err := ioutil.ReadDir(dir)</div><div class="line">	check(err)</div><div class="line">	<span class="keyword">var</span> files []<span class="keyword">string</span></div><div class="line">	<span class="keyword">for</span> _, path := <span class="keyword">range</span> paths &#123;</div><div class="line">		<span class="keyword">if</span> !path.IsDir() &#123;</div><div class="line">			files = <span class="built_in">append</span>(files, path.Name())</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="keyword">type</span> FileInfo <span class="keyword">struct</span> &#123;</div><div class="line">		FileName <span class="keyword">string</span></div><div class="line">		Len      <span class="keyword">int</span></div><div class="line">		Err      error</div><div class="line">	&#125;</div><div class="line">	way := <span class="built_in">make</span>(<span class="keyword">chan</span> FileInfo, <span class="number">100</span>)</div><div class="line">	<span class="keyword">for</span> _, file := <span class="keyword">range</span> files &#123;</div><div class="line">		<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">(fileName <span class="keyword">string</span>)</span></span> &#123;</div><div class="line">			content, err := ioutil.ReadFile(fmt.Sprintf(<span class="string">"%s/%s"</span>, dir, fileName))</div><div class="line">            <span class="comment">// 无论对错，都交给通道收取方</span></div><div class="line">			way &lt;- FileInfo&#123;</div><div class="line">				FileName: fileName,</div><div class="line">				Len:      <span class="built_in">len</span>(content),</div><div class="line">				Err:      err,</div><div class="line">			&#125;</div><div class="line">		&#125;(file)</div><div class="line">	&#125;</div><div class="line"></div><div class="line">    <span class="comment">// 我们知道需要从通道中取多少条数据</span></div><div class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="built_in">len</span>(files); i++ &#123;</div><div class="line">		fileInfo := &lt;-way</div><div class="line">		<span class="keyword">if</span> fileInfo.Err != <span class="literal">nil</span> &#123;</div><div class="line">			fmt.Printf(<span class="string">"[err] file:%s, err: %s \n"</span>, fileInfo.FileName, fileInfo.Err.Error())</div><div class="line">			<span class="keyword">return</span></div><div class="line">		&#125;</div><div class="line">		fmt.Printf(<span class="string">"file:%s, len: %d \n"</span>, fileInfo.FileName, fileInfo.Len)</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="并发读取文件夹所有文件的长度（使用sync-WaitGroup）"><a href="#并发读取文件夹所有文件的长度（使用sync-WaitGroup）" class="headerlink" title="并发读取文件夹所有文件的长度（使用sync.WaitGroup）"></a>并发读取文件夹所有文件的长度（使用sync.WaitGroup）</h2><p>这个使用的其实就是计数器的道理<br><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">test1</span><span class="params">()</span></span> &#123;</div><div class="line">	dir := <span class="string">"./db"</span></div><div class="line">	paths, err := ioutil.ReadDir(dir)</div><div class="line">	check(err)</div><div class="line">	<span class="keyword">var</span> files []<span class="keyword">string</span></div><div class="line">	<span class="keyword">for</span> _, path := <span class="keyword">range</span> paths &#123;</div><div class="line">		<span class="keyword">if</span> !path.IsDir() &#123;</div><div class="line">			files = <span class="built_in">append</span>(files, path.Name())</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">    <span class="comment">// sizes用来计算总长度和阻塞直至所有goroutine走完</span></div><div class="line">	sizes := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int64</span>)</div><div class="line">    <span class="comment">// 计数器</span></div><div class="line">	<span class="keyword">var</span> wg sync.WaitGroup</div><div class="line">	<span class="keyword">for</span> _, file := <span class="keyword">range</span> files &#123;</div><div class="line">		wg.Add(<span class="number">1</span>)</div><div class="line">		<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">(fileName <span class="keyword">string</span>)</span></span> &#123;</div><div class="line">			<span class="keyword">defer</span> wg.Done()</div><div class="line">			fileInfo, _ := os.Stat(fmt.Sprintf(<span class="string">"%s/%s"</span>, dir, fileName))</div><div class="line">			sizes &lt;- fileInfo.Size()</div><div class="line">		&#125;(file)</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</div><div class="line">		wg.Wait()</div><div class="line">		<span class="built_in">close</span>(sizes)</div><div class="line">	&#125;()</div><div class="line">	<span class="keyword">var</span> total <span class="keyword">int64</span></div><div class="line">	<span class="keyword">for</span> size := <span class="keyword">range</span> sizes &#123;</div><div class="line">		fmt.Printf(<span class="string">"size:%d\n"</span>, size)</div><div class="line">		total += size</div><div class="line">	&#125;</div><div class="line">	fmt.Printf(<span class="string">"total size: %d\n"</span>, total)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="令牌-另一种信号计数器"><a href="#令牌-另一种信号计数器" class="headerlink" title="令牌-另一种信号计数器"></a>令牌-另一种信号计数器</h2><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">check</span><span class="params">(err error)</span></span> &#123;</div><div class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</div><div class="line">		<span class="built_in">panic</span>(err)</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">	<span class="comment">// 链接列表</span></div><div class="line">	workList := <span class="built_in">make</span>(<span class="keyword">chan</span> []<span class="keyword">string</span>)</div><div class="line">	<span class="comment">// 存储已经处理的链接，使用map是为了去重</span></div><div class="line">	seen := <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="keyword">string</span>]<span class="keyword">bool</span>)</div><div class="line">	<span class="comment">// n是为了保证爬虫一直爬</span></div><div class="line">	n := <span class="number">1</span></div><div class="line">	<span class="comment">// 初始化 </span></div><div class="line">	<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123; workList &lt;- []<span class="keyword">string</span>&#123;<span class="string">"http://www.jianshu.com"</span>&#125; &#125;()</div><div class="line">	<span class="keyword">for</span> i := n; i &gt; <span class="number">0</span>; i++ &#123;</div><div class="line">		list := &lt;-workList</div><div class="line">		<span class="keyword">for</span> _, link := <span class="keyword">range</span> list &#123;</div><div class="line">			<span class="keyword">if</span> !seen[link] &#123;</div><div class="line">				seen[link] = <span class="literal">true</span></div><div class="line">				n++</div><div class="line">				<span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">(link <span class="keyword">string</span>)</span></span> &#123;</div><div class="line">					workList &lt;- crawl(link)</div><div class="line">				&#125;(link)</div><div class="line"></div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">var</span> tokens = <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">struct</span>&#123;&#125;, <span class="number">20</span>)</div><div class="line"></div><div class="line"><span class="comment">// 获取网页的链接  通过令牌</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">crawl</span><span class="params">(url <span class="keyword">string</span>)</span> <span class="params">(list []<span class="keyword">string</span>)</span></span> &#123;</div><div class="line">	fmt.Println(url)</div><div class="line">	tokens &lt;- <span class="keyword">struct</span>&#123;&#125;&#123;&#125;</div><div class="line">	list, err := Extract(url)</div><div class="line">	&lt;-tokens</div><div class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</div><div class="line">		log.Print(err)</div><div class="line">		<span class="keyword">return</span></div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 获取网页的链接</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">Extract</span><span class="params">(url <span class="keyword">string</span>)</span> <span class="params">(list []<span class="keyword">string</span>, err error)</span></span> &#123;</div><div class="line">	resp, err := http.Get(url)</div><div class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</div><div class="line">		<span class="keyword">return</span></div><div class="line">	&#125;</div><div class="line">	<span class="keyword">if</span> resp.StatusCode != http.StatusOK &#123;</div><div class="line">		resp.Body.Close()</div><div class="line">		<span class="keyword">return</span> <span class="literal">nil</span>, fmt.Errorf(<span class="string">"getting %s, err %s"</span>, url, err.Error())</div><div class="line">	&#125;</div><div class="line">	doc, err := html.Parse(resp.Body)</div><div class="line">	resp.Body.Close()</div><div class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">nil</span>, fmt.Errorf(<span class="string">"parsing %s as HTML, err %s"</span>, url, err.Error())</div><div class="line">	&#125;</div><div class="line">	visitNode := <span class="function"><span class="keyword">func</span><span class="params">(n *html.Node)</span></span> &#123;</div><div class="line">		<span class="keyword">if</span> n.Type == html.ElementNode &amp;&amp; n.Data == <span class="string">"a"</span> &#123;</div><div class="line">			<span class="keyword">for</span> _, a := <span class="keyword">range</span> n.Attr &#123;</div><div class="line">				<span class="keyword">if</span> a.Key != <span class="string">"href"</span> &#123;</div><div class="line">					<span class="keyword">continue</span></div><div class="line">				&#125;</div><div class="line">				link, err := resp.Request.URL.Parse(a.Val)</div><div class="line">				<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</div><div class="line">					<span class="keyword">continue</span></div><div class="line">				&#125;</div><div class="line">				list = <span class="built_in">append</span>(list, link.String())</div><div class="line">			&#125;</div><div class="line"></div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">// 将函数作为参数传入（匿名函数）</span></div><div class="line">	forEachNode(doc, visitNode, <span class="literal">nil</span>)</div><div class="line">	<span class="keyword">return</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">forEachNode</span><span class="params">(n *html.Node, pre, next <span class="keyword">func</span>(node *html.Node)</span>)</span> &#123;</div><div class="line">	<span class="keyword">if</span> pre != <span class="literal">nil</span> &#123;</div><div class="line">		pre(n)</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">for</span> n := n.FirstChild; n != <span class="literal">nil</span>; n = n.NextSibling &#123;</div><div class="line">		forEachNode(n, pre, next)</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">if</span> next != <span class="literal">nil</span> &#123;</div><div class="line">		next(n)</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/linux/zsh/" rel="next" title="zsh">
                <i class="fa fa-chevron-left"></i> zsh
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256"
               alt="chimps" />
          <p class="site-author-name" itemprop="name">chimps</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">59</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#并发编程示例"><span class="nav-number">1.</span> <span class="nav-text">并发编程示例</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#定时任务"><span class="nav-number">1.1.</span> <span class="nav-text">定时任务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#断续器"><span class="nav-number">1.2.</span> <span class="nav-text">断续器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#超时"><span class="nav-number">1.3.</span> <span class="nav-text">超时</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义定时器"><span class="nav-number">1.4.</span> <span class="nav-text">自定义定时器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用时间控制停止ticker"><span class="nav-number">1.5.</span> <span class="nav-text">使用时间控制停止ticker</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#并发读取文件夹所有文件的长度（使用通道）"><span class="nav-number">1.6.</span> <span class="nav-text">并发读取文件夹所有文件的长度（使用通道）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#并发读取文件夹所有文件的长度（使用sync-WaitGroup）"><span class="nav-number">1.7.</span> <span class="nav-text">并发读取文件夹所有文件的长度（使用sync.WaitGroup）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#令牌-另一种信号计数器"><span class="nav-number">1.8.</span> <span class="nav-text">令牌-另一种信号计数器</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chimps</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  
    
    <script>
      var cloudTieConfig = {
        url: document.location.href, 
        sourceId: "",
        productKey: "48bb30d8783d4b38ba0c95e0283238ca",
        target: "cloud-tie-wrapper"
      };
    </script>
    <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script>
  










  





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
